import { loginAPI, getUserProfileAPI, getUserInfoAPI } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'
const state = () => {
  return {
    // 刷新页面的时候，从本地取一份token，借助逻辑或短路运算符
    token: getToken() || '',
    userInfo: {}
  }
}
const mutations = {
  setToken: (state, token) => {
    // 设置token
    state.token = token
    // 本地在存一份token
    setToken(token)
  },
  // 设置用户信息
  setUserInfo: (state, userInfo) => {
    state.userInfo = userInfo
  },
  // 清空token
  removeToken: (state) => {
    state.token = ''
    // 清空本地token
    removeToken()
  },
  // 清空用户信息
  removeUserInfo: (state) => {
    state.userInfo = {}
  }
}

const actions = {
  loginAction: async({ commit }, loginForm) => {
    // 发起登录请求
    // 提交mutations
    const resp = await loginAPI(loginForm)
    console.log(resp)

    commit('setToken', resp.data)
  },
  // 获取用户信息action

  getUserInfoAction: async({ commit }) => {
    // 调接口发请求
    // const resp = await getUserProfileAPI()
    const { data: userProfile } = await getUserProfileAPI()
    // 基于此次接口返回的userId继续法请第二次请求（获取用户头像等信息}
    // console.log(userProfile)
    const { data: userInfo } = await getUserInfoAPI(userProfile.userId)
    // console.log(resp)
    // console.log(userInfo)
    const userObj = { ...userProfile, ...userInfo }
    // 提交mutation
    commit('setUserInfo', userObj)

    return userObj
  },
  logoutAction: ({ commit }) => {
    commit('removeToken')
    commit('removeUserInfo')
    // 重置路由实例（把路由表中所有信息删除清空）
    resetRouter()
    // 清空vuex中路由

    commit('route/removeRoutes', null, {
      // 从全局触发
      root: true
    })
    // 重置主题色
    commit('settings/resetTheme', null, {
      root: true
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
